import json

from django.http import HttpResponse
from django.utils.timezone import make_aware

from datetime import datetime, timedelta

from ...utils.data_handle import chatorders_handler

from ...models.chat_orders import ChatOrders


def order_list(request):
    '''
    POST
    {
        "order_no": "e2q0e29039012",
        "pay_time": [
            "2024-09-25",
            "2024-09-26"
        ],
        "status": -1,
        "page": 1,
        "page_size": 15
    }
    status: -1:全部。0:未支付。1:已扫码。2:已支付
    获取所有的订单
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        # 获取用户提交过来需要查询的参数
        search_dict = dict()

        if "order_no" in json_obj and json_obj['order_no']:
            search_dict["order_no"] = json_obj['order_no']

        if json_obj['pay_time'] and len(json_obj['pay_time']) == 2:
            start_date = make_aware(datetime.strptime(json_obj['pay_time'][0], "%Y-%m-%d"))
            end_date = make_aware(datetime.strptime(json_obj['pay_time'][1], "%Y-%m-%d")) + timedelta(days=1)

            search_dict["pay_time__gte"] = start_date
            search_dict["pay_time__lte"] = end_date

        if int(json_obj['status']) != -1:
            search_dict["status"] = json_obj['status']

        # 获取所有的订单
        all_chatorders = ChatOrders.objects.filter(**search_dict).order_by('-id')
        all_chatorders_data = chatorders_handler(all_chatorders, json_obj['page'], json_obj['page_size'])

        res_mes = {
            "code": 0,
            "data": all_chatorders_data
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)


def order_remove(request):
    '''
    删除订单
    '''
    re_id = request.GET.get('id')
    if int(re_id) > 0:
        try:
            del_obj = ChatOrders.objects.get(id=re_id)

            if del_obj.status == 2:
                res_mes = {
                    "code": 1,
                    "message": "已支付订单不允许删除！"
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)
            
            del_obj.delete()

            res_mes = {
                "code": 0
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
        except:
            res_mes = {
                "code": 1,
                "message": "没有这个订单！"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)

